<template>
  <div class="device_doc">
    <secret-upload-dialog
      @uploadComplete="init"
      saveInterFace="a/uploaddevicefilehistory/uploadDeviceFileHistory/save"
      moduleName="设备相关文档"
      module="deviceDoc"
      ref="secretUploadDialog"
    ></secret-upload-dialog>
    <one-title title="设备相关文档" @refreshData="refresh">
      <div class="mes_btn">
        <el-button
          v-btn-permission="'delete'"
          @click="handleDelete">
          <i class="iconfont icon-btn_delete"></i>
          删除
        </el-button>
        <el-button
          v-btn-permission="'relate'"
          @click="handleEdit">
          <i class="iconfont icon-btn_edit"></i>
          数据关联
        </el-button>
        <el-button
          v-btn-permission="'upload'"
          size="small"
          @click="showSecretUpload"
          type="primary">
          <i class="iconfont icon-btn_export"></i>
          上传
        </el-button>
      </div>
    </one-title>
    <div class="fixed_top_56">
      <mes-search-comp
        :searchList="tableColConfig"
        ref="mesSearch"
        :searchResult="searchCount"
        @searchInfo="search">
      </mes-search-comp>
      <div class="table_container">
        <el-table
          :data="listData.list"
          ref="tableNode"
          v-loading="isLoading"
          :max-height="tableMaxHeight"
          :row-class-name="({row}) => !selectItems.some((item) => item.id === row.id) || 'line_selected'"
          @row-click="row => $refs.tableNode.toggleRowSelection(row)"
          @sort-change="handleSortChange"
          @selection-change="handleSelectionChange"
          border
          stripe
          tooltip-effect="dark">
          <el-table-column
            width="40"
            type="selection"
            align="center">
          </el-table-column>
          <mes-col-comp
            v-for="(column,index) in columnList"
            :key="index"
            :column="column">
          </mes-col-comp>
          <el-table-column
            label="操作"
            show-overflow-tooltip
            :resizable="false"
            align="center"
            width="120">
            <template slot-scope="scope">
              <span class="jump_item"
                    @click.stop="$downByBlob(scope.row.uploadHistoryId, scope.row.fileName)">下载</span>
              <span class="jump_item"
                    v-if="$checkPreviewName(scope.row.fileName)&&$checkPreviewSize(scope.row.fileSize)"
                    @click.stop="$previewFile(scope.row.uploadHistoryId)">预览</span>
              <span class="jump_item is_disabled" v-else>预览</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <mes-pagination
        @updateData="init"
        :currentPage="listData.pageNo"
        :total="listData.count || 0"
        :pageSize="listData.pageSize">
      </mes-pagination>
    </div>
    <!--数据关联-->
    <el-dialog
      title="数据关联"
      :visible.sync="dialogVisible"
      v-dialogDrag
      :close-on-click-modal="false"
      customClass="mes_dialog">
      <div class="table_container">
        <el-table
          :data="selectItemsDialog"
          ref="tableDialogNode"
          border
          tooltip-effect="dark"
          class="table_dialog">
          <el-table-column
            :class-name="'static_col'"
            prop="fileName"
            label="上传文件名"
            :resizable="false"
            show-overflow-tooltip
            align="left">
            <template slot-scope="scope">
              <file-icon :fileName="scope.row.fileName"></file-icon>
              <span>{{scope.row.fileName}}</span>
            </template>
          </el-table-column>
          <el-table-column
            :class-name="'static_col'"
            prop="uploadDate"
            label="上传时间"
            :resizable="false"
            show-overflow-tooltip
            align="center"
            width="180">
          </el-table-column>
          <el-table-column
            :class-name="'static_col'"
            prop="uploadUser"
            label="上传用户"
            :resizable="false"
            show-overflow-tooltip
            width="180"
            align="center">
          </el-table-column>
          <el-table-column
            prop="deviceNames"
            label="关联设备"
            :resizable="false"
            show-overflow-tooltip
            align="select"
            width="230">
            <template slot-scope="scope">
              <el-select
                size="small"
                filterable
                multiple
                collapse-tags
                :multiple-limit="100"
                v-model="scope.row.selectedDeviceIDs"
                style="width: 100%"
                placeholder="请选择设备">
                <el-option
                  v-for="(item,index) in deviceList"
                  :key="index"
                  :label="item.NAME"
                  :value="item.ID">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <!--<el-table-column-->
            <!--label="操作"-->
            <!--show-overflow-tooltip-->
            <!--:resizable="false"-->
            <!--align="center"-->
            <!--fixed="right"-->
            <!--min-width="100">-->
            <!--<template slot-scope="scope">-->
              <!--<div class="operation">-->
                <!--<el-button type="text" size="small">-->
                  <!--<span class="jump_item" @click="$downByBlob(scope.row.uploadHistoryId, scope.row.fileName)">下载</span>-->
                <!--</el-button>-->
                <!--<el-button type="text" size="small">-->
                <!--<span class="jump_item" @click="$previewFile(scope.row.uploadHistoryId)"-->
                      <!--v-if=" $checkPreviewName(scope.row.fileName)&&$checkPreviewSize(scope.row.fileSize)">预览</span>-->
                  <!--<span v-else class="jump_item disicon">预览</span>-->
                <!--</el-button>-->
              <!--</div>-->
            <!--</template>-->
          <!--</el-table-column>-->
        </el-table>
      </div>
      <span slot="footer" class="mes_btn">
        <el-button type="primary" @click="saveRelative">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import FileIcon from '@/components/FileIcon'
import tableColumn from './tableColumn'

// 查询列表接口
let listInterFace = 'a/uploaddevicefilehistory/uploadDeviceFileHistory/list'
// 保存关联接口
let saveBatchInterFace = 'a/uploaddevicefilehistory/uploadDeviceFileHistory/dataRelate'
// 删除列表项接口
let deleteBatchInterFace = 'a/uploaddevicefilehistory/uploadDeviceFileHistory/deleteBatch'
export default {
  name: 'DeviceDoc',
  components: {
    FileIcon
  },
  data() {
    return {
      tableColConfig: tableColumn, // 列配置
      isLoading: true, // 数据加载中
      searchParams: {}, // 查询参数
      sortOrder: {deviceNames: 'desc'}, // 排序对象
      searchCount: NaN, // 搜索结果数
      selectItems: [], // 选中的数据
      selectItemsDialog: [], // 选中弹框中的数据,
      dialogVisible: false // 弹窗是否显示
    }
  },
  computed: {
    // 列表数据
    listData() {
      return this.$store.state.deviceDoc.listData
    },
    // 设备列表数据
    deviceList() {
      return this.$store.state.deviceDoc.deviceList
      // let tempStr = JSON.stringify(this.$store.state.generalProcessDoc.workGroupList)
      //   .replace(/id/g, 'value').replace(/name/g, 'label').replace(/workcenter/g, 'children')
      // return JSON.parse(tempStr)
    },
    // 列循环
    columnList() {
      return this.tableColConfig.filter(item => item.noForCol !== true && item.isShow !== false)
    },
  },
  mounted() {
    this.init()
    this.getDeviceList()
  },
  methods: {
    showSecretUpload() {
      this.$refs.secretUploadDialog.openDialog()
    },
    // 初始化方法
    init(page) {
      this.isLoading = true
      let pageObj = page || {
        pageNo: 1,
        pageSize: this.listData.pageSize || 15
      }
      let postData = {
        method: 'post',
        url: listInterFace,
        module: 'deviceDoc',
        data: {
          pageNo: pageObj.pageNo,
          pageSize: pageObj.pageSize,
          query: this.searchParams,
          sort: this.sortOrder
        },
        state: 'listData'
      }
      this.$store.dispatch('saveData', postData).then(res => {
        if (Object.keys(this.searchParams).length > 0) {
          this.searchCount = res.count
        } else {
          this.searchCount = NaN
        }
      }).finally(() => {
        this.isLoading = false
      })
    },
    // 获取设备列表
    getDeviceList() {
      let commitObj = {
        method: 'get',
        url: 'a/device/device/listfields/id,name,snumber',
        module: 'deviceDoc',
        state: 'deviceList'
      }
      this.$store.dispatch('saveData', commitObj)
    },
    // 搜索方法
    search(params) {
      this.searchParams = params
      this.init()
    },
    // 排序方法
    handleSortChange(e) {
      this.sortOrder = this.$getSortOrder(e)
      this.init()
    },
    // 刷新方法
    refresh() {
      this.searchParams = {} // 查询参数
      this.sortOrder = {deviceNames: 'desc'} // 排序对象
      this.$refs.mesSearch.clean()
      this.$refs.tableNode.clearSort()
      this.init()
    },
    // 选中方法
    handleSelectionChange(val) {
      val.map(item => {
        item.selectedDeviceIDs = item.deviceIds ? item.deviceIds.split(',') : []
      })
      this.selectItems = val
    },
    // 编辑方法
    handleEdit() {
      if (this.selectItems.length) {
        // 每次编辑时重置选择的数据
        this.selectItemsDialog = JSON.parse(JSON.stringify(this.selectItems))
        this.dialogVisible = true
      } else {
        this.$message.error({
          message: '未选择任何数据',
          duration: 1500,
          center: true
        })
      }
    },
    // 保存关联
    saveRelative() {
      let commitObj = {
        method: 'post',
        url: saveBatchInterFace,
        data: {uploadDeviceFileHistoryList: this.getEditedData()},
        noCommit: true
      }
      this.$store.dispatch('saveData', commitObj).then(() => {
        this.dialogVisible = false
        this.selectItemsDialog = []
        this.init()
      })
    },
    // 构造已编辑的关联
    getEditedData() {
      let arr = []
      this.selectItemsDialog.map(value => {
        if (value.selectedDeviceIDs) {
          arr.push({
            id: value.id,
            deviceIds: value.selectedDeviceIDs.join(',')
          })
        }
      })
      return arr
    },
    // 删除提示信息
    handleDelete() {
      if (this.selectItems.length) {
        this.confirmDelete().then(() => {
          this.deleteItems()
        }).catch(() => {
        })
      } else {
        this.$message.error({
          message: '未选择任何数据',
          duration: 1500,
          center: true
        })
      }
    },
    // 删除
    deleteItems() {
      let postData = {
        method: 'post',
        url: deleteBatchInterFace,
        module: 'deviceDoc',
        data: {
          uploadDeviceFileHistoryList: this.selectItems
        },
        noCommit: true
      }
      this.$store.dispatch('saveData', postData).then(() => {
        this.$message.success({
          message: '删除成功',
          duration: 1500,
          center: true
        })
        this.init(this.listData)
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .device_doc {
    .upload_button {
      margin-left: 10px;
    }

    .table_cascader {
      width: 100%;
    }

    .operation {
      span {
        cursor: pointer;
        font-size: 14px;

        &.disicon {
          cursor: not-allowed;
          color: #a1b1c1;
        }
      }
    }
  }
</style>
